﻿using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using System;
using System.Linq;
using System.Linq.Expressions;

namespace CommonUtils
{
    [Route("api/[controller]/[action]")]
    [ApiController]//不加这个dto默认不是postJson
    [Produces(ContentType.Json)]//加了这个,swagger就不用在[success media type]下拉选择返回类型了
    public class DbController<TDb, TEntity> : ControllerBase where TEntity : DbEntity where TDb : DbContextPlus<TDb>
    {
        public TDb DbInstance
        => DbContextPlus<TDb>.Instance;

        public static Expression<Func<TEntity, bool>> NewQuery()
        => DbContextPlus<TDb>.NewQuery<TEntity>();

        public static IOrderedQueryable<TEntity> NewOrder<TKey>(Expression<Func<TEntity, TKey>> keySelector)
        => DbContextPlus<TDb>.NewOrder(keySelector);

        public static IOrderedQueryable<TEntity> NewOrderDesc<TKey>(Expression<Func<TEntity, TKey>> keySelector)
        => DbContextPlus<TDb>.NewOrderDesc(keySelector);

        [HttpPost]
        [SwaggerOperation("保存")]
        public virtual ApiResult<TEntity> Save(TEntity item)
        => ApiResult.Ok(DbInstance.Save(item));

        [HttpPost]
        [SwaggerOperation("批量保存")]
        public virtual ApiResult<TEntity[]> SaveBatch(TEntity[] items)
        => ApiResult.Ok(DbInstance.Save(items));

        [HttpDelete]
        [SwaggerOperation("删除")]
        public virtual ApiResult<bool> Delete(TEntity item)
        => ApiResult.Ok(DbInstance.Delete(item));

        [HttpDelete]
        [SwaggerOperation("批量删除")]
        public virtual ApiResult<int> DeleteBatch(TEntity[] items)
        => ApiResult.Ok(DbInstance.Delete(items));
    }
}